<template>
  <div class="studyRole-Box">
    <NewCard title="学习角色" :border="false">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="删除" width="45">
          <template slot-scope="scope">
            <i class="el-icon-remove-outline removeRole" @click="removeRole(scope.row)"></i>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色" width="150">
        </el-table-column>
        <el-table-column prop="type" label="角色类别" width="150">
          <template slot-scope="scope">
            <p>{{ scope.row.type == "0" ? "系统角色" : "自定义角色   " }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="studentNum" label="人数" width="150">
        </el-table-column>
        <el-table-column prop="subject" label="科目">
          <template slot-scope="scope">
            <!-- @hide="selectTableHide(scope.row)" 关闭弹出框的时候隐藏 -->
            <el-popover
              placement="bottom-start"
              width="600"
              trigger="click"
              @hide="selectTableHide(scope.row)"
            >
              <!-- 多选框 -->
              <el-checkbox-group
                v-model="scope.row.examIdList"
                v-if="subjectList.length"
                @change="checkTableSub(scope.row)"
              >
                <el-checkbox
                  :label="sub.id"
                  v-for="(sub, index) in subjectList"
                  :key="index"
                  >{{ sub.name }}</el-checkbox
                >
              </el-checkbox-group>
              <p v-else>暂无科目</p>

              <!-- 已选的 -->
              <div class="subAdd" slot="reference">
                <svg-icon icon-class="add-icon" />
                <span v-for="(list, index) in scope.row.examList" :key="index">
                  {{ list.second
                  }}<i v-if="scope.row.examList.length != index + 1">、</i>
                </span>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          prop="statusStudy"
          label="状态"
          width="150"
          align="right"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.statusStudy"
              active-color="#f87a23"
              active-value="0"
              inactive-value="1"
              @change="changeStatusStudy(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 40]"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageing.total"
        >
        </el-pagination>
      </div>

      <!-- 添加按钮 -->
      <div class="addBox" v-hasPermi="['system:role:list']">
        <el-button type="primary" v-if="addBtnShow" @click="clickAddBtn"
          >+ 添加角色</el-button
        >
        <div class="addForm" v-else>
          <el-select v-model="addFrom.type" placeholder="请选择">
            <el-option label="系统角色" value="0"></el-option>
            <el-option label="自定义角色" value="1"></el-option>
          </el-select>
          <el-select
            v-model="addFrom.roleId"
            placeholder="请选择"
            v-if="addFrom.type == '0'"
          >
            <el-option
              :label="role.roleName"
              :value="role.roleId"
              v-for="(role, index) in roleList"
              :key="index"
            ></el-option>
          </el-select>
          <el-input
            v-model="addFrom.roleName"
            placeholder="请输入角色名称"
            v-else
          ></el-input>
          <el-button type="primary" class="addBtn" round @click="subAddBtn"
            >确认添加</el-button
          >
          <el-button round @click="clickCancel">取消</el-button>
        </div>
      </div>
    </NewCard>
  </div>
</template>

<script>
import NewCard from "@/wss/components/newCard.vue";
import {
  getExamRoleListApi,
  editRoleChangeStatusApi,
  getRoleListApi,
  editStudyRoleApi,
  addStudyRoleApi,
  getExamListApi,
  examRoleBindExamApi,
  examRoleUnbindExamApi,
  deleteStudyRoleApi
} from "@/wss/newApi_3-24/assess/exam.js";
import debounce from "lodash/debounce";
export default {
  name: "studyRole",
  components: { NewCard },
  data() {
    return {
      // 分页
      pageing: { pageNum: 1, pageSize: 10, total: 0 },
      // 表格
      tableData: [],

      // 选择科目
      subjectList: [],
      addBtnShow: true, //添加角色按钮显示隐藏
      roleList: [], //系统用户的列表
      // 添加表单
      addFrom: {
        type: "0",
        roleId: "",
        roleName: ""
      }
    };
  },
  mounted() {
    this.getExamRoleList(); // 获取全部学习角色
    this.getRoleList(); // 查询所有系统用户
    this.getExamList(); // 查询所有科目
  },
  methods: {
    // 分页器 每页多少条
    handleSizeChange(val) {
      this.pageing.pageSize = val;
      this.getExamRoleList(); // 获取全部学习角色
    },

    // 分页器 第几页
    handleCurrentChange(val) {
      this.pageing.pageNum = val;
      this.getExamRoleList(); // 获取全部学习角色
    },

    // 获取全部学习角色
    async getExamRoleList() {
      let result = await getExamRoleListApi(this.pageing);
      if (result.code == 200) {
        let dataArr = JSON.parse(JSON.stringify(result.rows));
        dataArr.forEach(item => {
          item.examIdList = [];
          item.examList.forEach(exa => {
            item.examIdList.push(exa.first);
          });
        });
        this.tableData = JSON.parse(JSON.stringify(dataArr));
        this.pageing.total = result.total;
      }
    },

    // 查询所有系统用户
    async getRoleList() {
      let result = await getRoleListApi();
      if (result.code == 200) {
        // 过滤出type=0的系统角色
        let newArr = result.rows.filter(item => {
          return item.type != "1";
        });
        this.roleList = JSON.parse(JSON.stringify(newArr));
      }
    },

    // 添加自定义角色
    async addStudyRole() {
      let data = {};
      if (this.addFrom.type == "0") {
        data.roleId = this.addFrom.roleId;
      } else {
        data.roleName = this.addFrom.roleName;
      }
      let result = await addStudyRoleApi([data]);
      if (result.code == 200) {
        this.$message({ type: "success", message: "添加成功" });
      }
    },

    // 点击删除按钮
    removeRole: debounce(function(row){
      this.$confirm('是否删除该学习角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteStudyRole(row.roleId) // 删除学习角色
      }).catch(() => {});
    },300),

    // 删除学习角色
    async deleteStudyRole(roleIds){
      let result = await deleteStudyRoleApi({roleIds})
      if (result.code == 200) {
        this.getExamRoleList(); // 获取全部学习角色
        this.$message({ type: "success", message: "删除成功" });
      }
    },

    // 查询所有科目
    async getExamList() {
      let result = await getExamListApi();
      if (result.code == 200) {
        this.subjectList = result.rows;
      }
    },

    // 勾选多选框的时候
    checkTableSub(row) {
      row.examList = []; //直接清空
      row.examIdList.forEach(item => {
        let obj = this.subjectList.find(sub => {
          return sub.id == item;
        });
        row.examList.push({
          first: obj.id,
          second: obj.name
        });
      });
    },

    // 绑定学习角色
    async examRoleBindExam(data) {
      let result = await examRoleBindExamApi(data);
      if (result.code == 200) {
        this.$message({ type: "success", message: "编辑成功" });
      }
    },

    // 勾选完成关闭弹出框的时候去保存
    selectTableHide(row) {
      // 学习id 数组
      let examIds = [];
      row.examList.forEach(item => {
        examIds.push(item.first); //id
      });
      // 整理数据
      let data = {
        roleId: row.roleId,
        examIds: examIds
      };
      this.examRoleBindExam(data); //发请求
    },

    // 开启和关闭学习角色的接口
    async editRoleChangeStatus(data) {
      let result = await editRoleChangeStatusApi(data);
      if (result.code == 200) {
        this.$message({ type: "success", message: "编辑成功" });
      }
    },

    // 修改学习角色的状态
    changeStatusStudy(row) {
      let data = {
        roleId: row.roleId,
        statusStudy: row.statusStudy
      };
      this.editRoleChangeStatus(data);
    },

    // ------------------按钮区------------------
    // 点击添加角色
    clickAddBtn() {
      this.addBtnShow = false;
    },

    // 点击确认添加
    async subAddBtn() {
      if (this.addFrom.type == "0") {
        if (!this.addFrom.roleId) {
          this.$message({ type: "warning", message: "请选择系统角色" });
          return;
        }
        // 系统角色
        await this.addStudyRole(); // 添加系统角色 是修改
        this.getExamRoleList(); // 获取全部学习角色
      } else if (this.addFrom.type == "1") {
        if (!this.addFrom.roleName) {
          this.$message({ type: "warning", message: "请填写角色名称" });
          return;
        }
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].roleName == this.addFrom.roleName) {
            this.$message({ type: "error", message: "角色名称请勿相同" });
            return;
          }
        }
        // 自定义角色
        await this.addStudyRole(); // 添加系统角色 是修改
        this.getExamRoleList(); // 获取全部学习角色
      }
    },

    // 点击取消按钮
    clickCancel() {
      this.addBtnShow = true;
    }
  }
};
</script>

<style scoped lang="scss">
.studyRole-Box {
  height: 100%;
  .el-card {
    position: relative;
  }
}
.subAdd {
  cursor: pointer;
  svg {
    margin-right: 5px;
  }
}

// 删除按钮
.removeRole{
  cursor: pointer;
}

// 添加按钮
.addBox {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 999;
  .el-button {
    width: 100%;
    border: 0;
    border-top: 1px solid #ecedf0;
    background-color: #f8f8f8;
    line-height: 25px;
    color: #606e84;
  }
  .addForm {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    border-top: 1px solid #ecedf0;
    background-color: #f8f8f8;
    padding: 10px 0;
    .el-select,
    .el-input {
      width: 14%;
      margin: 0 5px;
    }
    .el-button {
      width: 100px;
      padding: 5px 0;
      background-color: #fff;
      border: 1px solid #ecedf0;
    }
    .addBtn {
      background-color: #f87a23;
      border-color: #f87a23;
      color: #fff;
    }
  }
}
</style>

<style scoped>
.studyRole-Box >>> .el-card__body {
  height: 100%;
}
.studyRole-Box >>> .el-card__body > div {
  height: calc(100% - 45px);
  overflow-y: auto;
}
.studyRole-Box >>> .el-card__body > div::-webkit-scrollbar {
  width: 0;
}

/* 表格样式 */
::v-deep .el-table::before {
  height: 0;
}
::v-deep .el-table .el-table__header-wrapper th {
  background-color: #fff;
}
::v-deep .el-table th.is-leaf {
  border-top: 1px solid #efefef;
  border-bottom: 1px solid #efefef;
}
::v-deep .el-table th > .cell {
  font-size: 12px;
  color: #909aaa;
}
::v-deep .el-table .cell,
::v-deep .el-table .cell p {
  margin: 0;
  font-size: 14px;
  color: #2e3f5e;
}
::v-deep .el-table .cell .el-button {
  color: #f87a23;
}
::v-deep .el-table .cell .el-table__expand-icon i::before {
  content: "\E791";
}
::v-deep .el-table td {
  /* border-bottom: 0; */
}
::v-deep .el-table td .islight {
  color: #f87a23;
  cursor: pointer;
}
::v-deep .el-table .el-table__expanded-cell[class*="cell"] {
  padding: 0;
}
::v-deep .el-table__expanded-cell .el-table::before {
  height: 0;
}
::v-deep .el-table__expanded-cell .el-table th.is-leaf {
  border-top: 0;
}
::v-deep .el-table__expanded-cell .el-table td {
  border-bottom: 0;
}
/* 表格样式 end */

/* 多选框 */
.el-checkbox-group .el-checkbox {
  width: 18%;
  margin: 10px 0;
  margin-right: 10px;
}
.el-checkbox-group .el-checkbox:nth-child(5n) {
  margin-right: 0;
}
/* 多选框 end */

.pagination {
  margin-top: 20px;
  margin-bottom: 60px;
  text-align: center;
}
</style>
